<template>
  <div class="pressure-heatmap">
    <!-- 坐标轴标签 -->
    <div class="axis-labels">
      <!-- X轴标签 -->
      <div class="x-axis">
        <div class="x-label" v-for="x in 10" :key="x">{{ x }}</div>
      </div>
      
      <!-- 热图网格 -->
      <div class="heatmap-grid">
        <!-- Y轴标签 -->
        <div class="y-axis">
          <div class="y-label" v-for="y in 10" :key="y">{{ y }}</div>
        </div>
        
        <!-- 热图单元格 -->
        <div class="grid-container">
          <div v-for="row in 10" :key="row" class="grid-row">
            <div 
              v-for="col in 10" 
              :key="col"
              :class="['grid-cell', getCellClass(row, col)]"
              @click="handleCellClick(row, col)"
            >
              {{ getTileValue(row, col) }}
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 图例 -->
    <div class="legend">
      <div class="legend-title">压力传感器数值 (21传感器模式)</div>
      <div class="legend-item">
        <div class="legend-color pressure-inactive"></div>
        <span class="legend-label">无压力 (0-10)</span>
      </div>
      <div class="legend-item">
        <div class="legend-color pressure-normal"></div>
        <span class="legend-label">轻微压力 (10-100)</span>
      </div>
      <div class="legend-item">
        <div class="legend-color pressure-warning"></div>
        <span class="legend-label">中等压力 (100-200)</span>
      </div>
      <div class="legend-item">
        <div class="legend-color pressure-critical"></div>
        <span class="legend-label">高压力 (≥200)</span>
      </div>
      <div class="legend-item">
        <div class="legend-color inactive-tile"></div>
        <span class="legend-label">非活动区域</span>
      </div>
    </div>
  </div>
</template>

<script>
import smartTileApi from '@/api/smartTileApi'

export default {
  name: 'PressureHeatmap',
  props: {
    data: {
      type: Array,
      required: true
    },
    autoRefresh: {
      type: Boolean,
      default: true
    },
    refreshInterval: {
      type: Number,
      default: 1000 // 1秒刷新一次
    }
  },
  data() {
    return {
      refreshTimer: null,
      realTimeData: null
    }
  },
  mounted() {
    if (this.autoRefresh) {
      this.startAutoRefresh()
    }
  },
  beforeUnmount() {
     this.stopAutoRefresh()
   },
   computed: {
     // 使用实时数据或传入的props数据
     currentData() {
       return this.realTimeData || this.data
     }
   },
   methods: {
     /**
      * 开始自动刷新
      */
     startAutoRefresh() {
       this.loadRealTimeData() // 立即加载一次
       this.refreshTimer = setInterval(() => {
         this.loadRealTimeData()
       }, this.refreshInterval)
     },
     
     /**
      * 停止自动刷新
      */
     stopAutoRefresh() {
       if (this.refreshTimer) {
         clearInterval(this.refreshTimer)
         this.refreshTimer = null
       }
     },
     
     /**
      * 加载实时数据
      */
     async loadRealTimeData() {
       try {
         const response = await smartTileApi.getRealSensorData()
         if (response && response.success && response.data && response.data.heatmap) {
           // 提取热图数据
           this.realTimeData = response.data.heatmap
           this.$emit('data-updated', response)
         }
       } catch (error) {
         console.warn('加载实时数据失败:', error)
         // 失败时继续使用props数据
       }
     },
    /**
     * 判断是否为活动瓷砖区域 (3x7的中心区域)
     * @param {number} row - 行索引 (1-10)
     * @param {number} col - 列索引 (1-10)
     * @returns {boolean}
     */
    isActiveTile(row, col) {
      // 3x7区域位于10x10网格的中心位置
      // 行: 4-6 (第4、5、6行)
      // 列: 2-8 (第2、3、4、5、6、7、8列)
      return row >= 4 && row <= 6 && col >= 2 && col <= 8
    },
    
    /**
      * 获取单元格的CSS类
      * @param {number} row - 行索引
      * @param {number} col - 列索引
      * @returns {string}
      */
     getCellClass(row, col) {
       if (!this.isActiveTile(row, col)) {
         return 'inactive-tile'
       }
       
       const pressure = this.getTileValue(row, col, true)
        // 调整阈值以适应传感器原始数值范围（0-1023）
        if (pressure >= 200) return 'pressure-critical'  // 高压力：200以上
        if (pressure >= 100) return 'pressure-warning'   // 中等压力：100-200
        if (pressure > 10) return 'pressure-normal'      // 轻微压力：10-100
        return 'pressure-inactive'  // 无压力：0-10
     },
    
    /**
     * 获取瓷砖的压力值
     * @param {number} row - 行索引 (1-10)
     * @param {number} col - 列索引 (1-10)
     * @param {boolean} returnNumber - 是否返回数值
     * @returns {string|number}
     */
    getTileValue(row, col, returnNumber = false) {
      if (!this.isActiveTile(row, col)) {
        return returnNumber ? 0 : ''
      }
      
      // 将10x10坐标转换为3x7数组索引
       const tileRow = row - 4  // 转换为0-2
       const tileCol = col - 2  // 转换为0-6
      
      // 从currentData数组中获取对应的压力值
       if (this.currentData && this.currentData.length > tileRow && this.currentData[tileRow].length > tileCol) {
         const cellData = this.currentData[tileRow][tileCol]
         const pressure = parseFloat(cellData.pressure || 0)
         return returnNumber ? pressure : pressure.toFixed(0)
       }
      
      return returnNumber ? 0 : '0.0'
    },
    
    /**
     * 处理单元格点击事件
     * @param {number} row - 行索引
     * @param {number} col - 列索引
     */
    handleCellClick(row, col) {
      if (!this.isActiveTile(row, col)) {
        return
      }
      
      const tileRow = row - 4
      const tileCol = col - 2
      
      if (this.currentData && this.currentData.length > tileRow && this.currentData[tileRow].length > tileCol) {
         const cellData = this.currentData[tileRow][tileCol]
         this.$emit('cell-click', {
           ...cellData,
           gridRow: row,
           gridCol: col,
           tileRow: tileRow + 1,
           tileCol: tileCol + 1
         })
       }
    }
  }
}
</script>

<style scoped>
.pressure-heatmap {
  position: relative;
}

.axis-labels {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.x-axis {
  display: flex;
  gap: 98px;
  margin-left: 52px;
  margin-bottom: 4px;
}

.x-label {
  color: #6B7280;
  font-size: 14px;
  line-height: 21px;
  width: 18px;
  text-align: center;
}

.heatmap-grid {
  display: flex;
  gap: 4px;
}

.y-axis {
  display: flex;
  flex-direction: column;
  gap: 4px;
  width: 32px;
}

.y-label {
  color: #6B7280;
  font-size: 14px;
  line-height: 21px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding-right: 16px;
}

.grid-container {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.grid-row {
  display: flex;
  gap: 4px;
}

.grid-cell {
  width: 100px;
  height: 28px;
  border: 1px solid #E5E7EB;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
}

.grid-cell:hover {
  transform: scale(1.05);
  z-index: 10;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 活动瓷砖区域样式 - 压力值越大颜色越深 */
    .pressure-inactive {
      background: rgba(108, 117, 125, 0.2);
      color: #6c757d;
      border-color: #dee2e6;
    }
    
    .pressure-normal {
      background: rgba(82, 196, 26, 0.60);
      color: #155724;
      border-color: #c3e6cb;
    }
    
    .pressure-warning {
      background: rgba(250, 173, 20, 0.75);
      color: #856404;
      border-color: #fdcb6e;
    }
    
    .pressure-critical {
      background: rgba(255, 77, 79, 0.90);
      color: #721c24;
      border-color: #dc3545;
    }

/* 非活动区域样式 - 灰色 */
.inactive-tile {
  background-color: #e9ecef;
  color: #6c757d;
  border-color: #dee2e6;
  cursor: default;
}

.inactive-tile:hover {
  border-color: #dee2e6;
  transform: none;
  box-shadow: none;
}

.cell-value {
  color: #FFFFFF;
  font-weight: 500;
  font-size: 14px;
  line-height: 21px;
}

.legend {
  position: absolute;
  bottom: -8px;
  right: 30px;
  background: rgba(255, 255, 255, 0.90);
  box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.05);
  border-radius: 6px;
  padding: 12px 16px;
  display: flex;
  gap: 8px;
  align-items: center;
}

.legend-title {
  font-weight: bold;
  font-size: 14px;
  color: #495057;
  margin-right: 12px;
}

.legend-item {
  display: flex;
  align-items: center;
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 3px;
  margin-right: 6px;
}

.legend-label {
  color: #4B5563;
  font-size: 14px;
  line-height: 21px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .x-axis {
    gap: 60px;
    margin-left: 40px;
  }
  
  .grid-cell {
    width: 80px;
    height: 24px;
  }
  
  .y-axis {
    width: 28px;
  }
}

@media (max-width: 768px) {
  .x-axis {
    gap: 40px;
    margin-left: 30px;
  }
  
  .grid-cell {
    width: 60px;
    height: 20px;
  }
  
  .cell-value {
    font-size: 12px;
  }
  
  .legend {
    position: static;
    margin-top: 16px;
    justify-content: center;
  }
}
</style>
